package icu.d4peng.basic.message.mail;

import icu.d4peng.basic.core.util.JacksonUtil;
import icu.d4peng.basic.message.mail.properties.MailProperties;
import icu.d4peng.basic.message.mail.service.MailService;
import icu.d4peng.basic.message.mail.service.impl.MailServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.Assert;

import javax.activation.MimeType;
import javax.mail.internet.MimeMessage;

/**
 * MailSenderAutoConfiguration:邮件服务自动配置
 *
 * @author d4peng <a href="d4peng@qq.com">d4peng@qq.com</a>
 * @since 2023.12.03
 */
@AutoConfiguration
@ConditionalOnClass({MimeMessage.class, MimeType.class, MailSender.class})
@ConditionalOnMissingBean(JavaMailSender.class)
@EnableConfigurationProperties(MailProperties.class)
@ConditionalOnProperty(prefix = MailProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class MailSenderAutoConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailSenderAutoConfiguration.class);

    public MailSenderAutoConfiguration(MailProperties mailProperties) {
        LOGGER.info("MailProperties:{}", JacksonUtil.toJson(mailProperties));
        Assert.notNull(mailProperties.getHost(), "host can't be null!");

    }

    @Bean
    @ConditionalOnMissingBean({MailService.class})
    public MailService mailService(MailProperties mailProperties, TaskExecutor taskExecutor) {
        return new MailServiceImpl(mailProperties, taskExecutor);
    }

}
